package com.qf.util;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import com.qf.bean.Role;
import com.qf.dao.MenuMapper;
import com.qf.dao.RoleMapper;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jws.Oneway;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 2019/11/26
 * Administrator
 * ssm1119
 * 面向对象面向君  不负代码不负卿
 */
public class MyForm extends FormAuthenticationFilter {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override  //当登录成功（认证成功）的时候被调用
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {
        System.out.println("onLoginSuccess开始");
        //1.先得到用户的信息（用户名和密码）
        Employee emp =(Employee) subject.getPrincipal();
        //2.根据用户名查询角色
        Role role = roleMapper.selectByPrimaryKey(emp.getRoleid());
        //3.根据角色查询菜单
        //2.根据角色信息查询角色所对应的菜单列表
        List<Menu> menus = menuMapper.findMenusByRoleid(role.getRoleid());//未分级
        //2.1 对菜单列表分级
        ArrayList firstMenu= new ArrayList();//保存一级菜单
        for (Menu menu : menus) {
            if(menu.getUpmenuId()==0){ //一级菜单
                ArrayList secondList= new ArrayList();//保存二级菜单
                for (Menu second : menus) {
                    if(menu.getMenuId()==second.getUpmenuId()){//如果一级菜单的id(menuid)==二级菜单的父id(upmenuid)
                        secondList.add(second);
                    }
                }
                //将二级菜单的集合封装到一级菜单中
                menu.setSecondMenu(secondList);
                //将一级菜单在添加到集合中
                firstMenu.add(menu);
            }
        }

        //3.将菜单赋值给角色，角色再赋值给用户
        role.setMenus(firstMenu);

        //将角色付给用户
        emp.setRole(role);
        //使用session存值
        HttpServletRequest req=(HttpServletRequest)request;
        req.getSession().setAttribute("user",emp);
        HttpServletResponse resp=(HttpServletResponse)response;
        System.out.println("onLoginSuccess结束");
        resp.sendRedirect("/index.jsp");
        return false;
    }
}
